import fs from 'fs'
import { fileURLToPath } from 'url'

export function queryCtrlJs() {
    let ctrlPath = new URL("../controller", import.meta.url).href
    let ctrlPath2 = fileURLToPath(ctrlPath)
    let ctrlArr = fs.readdirSync(ctrlPath2)
    const ctrlJs = ctrlArr.filter(item => item.endsWith("Controller.js")).map(file => `${ctrlPath}/${file}`)
    // console.log(ctrlJs);

    return ctrlJs;

}

export function registerRouter(router, ctrlJs) {
    ctrlJs.forEach(async item => {
        const { users } = await import(item)
        // console.log(users);

        users.forEach(user => {
            const reqMethod = user.method;
            const reqPath = user.path;
            const reqFn = user.fn;

            if (reqMethod === 'get') {
                router.get(reqPath, reqFn)
            }
            if (reqMethod === 'delete') {
                router.delete(reqPath, reqFn)
            }
            if (reqMethod === 'post') {
                router.post(reqPath, reqFn)
            }
            if (reqMethod === 'put') {
                router.put(reqPath, reqFn)
            }

        });

    });
}